package mylib

// 基础包
import (
	"fmt"
	"path"

	"github.com/henrylee2cn/pholcus/app/downloader/request" //必需
	. "github.com/henrylee2cn/pholcus/app/spider"           //必需
	"github.com/henrylee2cn/pholcus/common/goquery"         //DOM解析
)

func init() {
	LoroPiana.Register()
}

type news struct {
	module string //模块
	title  string //标题
	href   string //连接
	top    string
}

var LoroPiana = &Spider{
	Name:        "淘宝",
	Description: "女装-连衣裙",
	// Pausetime: 300,
	// Keyin:   KEYIN,
	// Limit:        LIMIT,
	EnableCookie: false,

	RuleTree: &RuleTree{
		Root: func(ctx *Context) {
			ctx.AddQueue(&request.Request{
				Method: "GET",
				Url:    "https://item.taobao.com/item.htm?spm=a219r.lm874.14.1.f370938OtiWJs&id=549096011576&ns=1&abbucket=14#detail",
				Rule:   "搜索页面",
			})
		},

		Trunk: map[string]*Rule{
			"搜索页面": {

				ParseFunc: func(ctx *Context) {
					fmt.Println("搜索页面")

					dom := ctx.GetDom()
					//商品名称
					list_table, ok := dom.Find(".tb-main-title").Attr("data-title")
					fmt.Println(list_table, ok)
					//价格
					price := dom.Find(".tb-property-cont .tb-rmb-num").Text()
					fmt.Println(price)
					//评论数
					rate_counter := dom.Find(".tb-rate-counter strong").Text()
					fmt.Println(rate_counter)
					//老板名称
					title_name, ok := dom.Find(".tb-shop-info-wrap strong a").Attr("title")
					fmt.Println(title_name, ok)

					// list_table.Each(func(i int, s *goquery.Selection) {

					// })
				},
			},

			"房屋信息": {
				ParseFunc: func(ctx *Context) {
					//fmt.Println("房屋信息")
					dom := ctx.GetDom()
					guide_map := dom.Find(".thumbnail li")

					guide_map.Each(func(i int, s *goquery.Selection) {
						data_src, ok := s.Find("img").Attr("src")
						if ok {
							dir, ok := s.Attr("data-desc")
							if !ok {
								dir = "未知"
							}
							ctx.AddQueue(&request.Request{
								Url:  data_src,
								Rule: "图片地址",
								Temp: map[string]interface{}{
									"dir": dir,
								},
							})
						}
					})
				},
			},
			"图片地址": {
				ParseFunc: func(ctx *Context) {

					_, baseName := path.Split(ctx.GetUrl())

					dir := ctx.GetTemp("dir", "").(string)
					//fmt.Println(baseName, dir)

					ctx.FileOutput(dir + "/" + baseName)
				},
			},
		},
	},
}
